<template>
  <div class="admin-container">
    <div class="admin-content animate__animated animate__fadeIn">
      <!-- 头部导航 -->
      <header class="admin-header">
        <div class="header-content">
          <h1 class="logo">管理员控制台</h1>
          <div class="user-menu">
            <span class="welcome-text">{{ authStore.username }} (管理员)</span>
            <button @click="goToUserDashboard" class="btn btn-secondary">
              用户视图
            </button>
            <button @click="handleLogout" class="btn btn-secondary logout-btn">
              退出登录
            </button>
          </div>
        </div>
      </header>

      <!-- 统计卡片 -->
      <div class="stats-section animate__animated animate__fadeInUp">
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">👥</div>
            <div class="stat-info">
              <h3>总用户数</h3>
              <p class="stat-number">{{ dashboardData.totalUsers || 0 }}</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">👤</div>
            <div class="stat-info">
              <h3>普通用户</h3>
              <p class="stat-number">{{ dashboardData.userCount || 0 }}</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-info">
              <h3>管理员</h3>
              <p class="stat-number">{{ dashboardData.adminCount || 0 }}</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">✅</div>
            <div class="stat-info">
              <h3>活跃用户</h3>
              <p class="stat-number">{{ dashboardData.enabledUsers || 0 }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户管理 -->
      <div class="users-section animate__animated animate__fadeInUp animate__delay-1s">
        <div class="section-header">
          <h2>用户管理</h2>
          <div class="filter-buttons">
            <button 
              @click="filterUsers('ALL')" 
              :class="['btn', 'btn-filter', { active: currentFilter === 'ALL' }]"
            >
              全部用户
            </button>
            <button 
              @click="filterUsers('USER')" 
              :class="['btn', 'btn-filter', { active: currentFilter === 'USER' }]"
            >
              普通用户
            </button>
            <button 
              @click="filterUsers('ADMIN')" 
              :class="['btn', 'btn-filter', { active: currentFilter === 'ADMIN' }]"
            >
              管理员
            </button>
          </div>
        </div>

        <div class="users-table-container">
          <table class="users-table">
            <thead>
              <tr>
                <th>用户名</th>
                <th>角色</th>
                <th>状态</th>
                <th>注册时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in filteredUsers" :key="user.id" class="user-row">
                <td class="username">{{ user.username }}</td>
                <td>
                  <span :class="['role-badge', user.role.toLowerCase()]">
                    {{ user.role === 'ADMIN' ? '管理员' : '普通用户' }}
                  </span>
                </td>
                <td>
                  <span :class="['status-badge', user.enabled ? 'enabled' : 'disabled']">
                    {{ user.enabled ? '已启用' : '已禁用' }}
                  </span>
                </td>
                <td class="date">{{ formatDate(user.createdAt) }}</td>
                <td class="actions">
                  <select 
                    :value="user.role" 
                    @change="updateUserRole(user.id, $event.target.value)"
                    class="role-select"
                    :disabled="user.username === authStore.username"
                  >
                    <option value="USER">普通用户</option>
                    <option value="ADMIN">管理员</option>
                  </select>
                  
                  <button 
                    @click="toggleUserStatus(user)"
                    :class="['btn', 'btn-sm', user.enabled ? 'btn-danger' : 'btn-success']"
                    :disabled="user.username === authStore.username"
                  >
                    {{ user.enabled ? '禁用' : '启用' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 背景装饰 -->
    <div class="background-shapes">
      <div class="bg-shape bg-shape-1"></div>
      <div class="bg-shape bg-shape-2"></div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { adminAPI } from '@/api/auth'

export default {
  name: 'AdminDashboard',
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()
    
    const dashboardData = reactive({
      totalUsers: 0,
      adminCount: 0,
      userCount: 0,
      enabledUsers: 0
    })
    
    const users = ref([])
    const currentFilter = ref('ALL')
    const loading = ref(false)
    
    const filteredUsers = computed(() => {
      if (currentFilter.value === 'ALL') {
        return users.value
      }
      return users.value.filter(user => user.role === currentFilter.value)
    })
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    }
    
    const loadDashboardData = async () => {
      try {
        const response = await adminAPI.getDashboard()
        Object.assign(dashboardData, response.data)
      } catch (error) {
        console.error('获取统计信息失败:', error)
      }
    }
    
    const loadUsers = async () => {
      try {
        loading.value = true
        const response = await adminAPI.getAllUsers()
        users.value = response.data
      } catch (error) {
        console.error('获取用户列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    const filterUsers = async (filter) => {
      currentFilter.value = filter
      
      if (filter === 'ALL') {
        await loadUsers()
      } else {
        try {
          loading.value = true
          const response = await adminAPI.getUsersByRole(filter)
          users.value = response.data
        } catch (error) {
          console.error('筛选用户失败:', error)
        } finally {
          loading.value = false
        }
      }
    }
    
    const updateUserRole = async (userId, newRole) => {
      try {
        await adminAPI.updateUserRole(userId, newRole)
        // 重新加载用户列表
        await filterUsers(currentFilter.value)
        await loadDashboardData()
      } catch (error) {
        console.error('更新用户角色失败:', error)
        alert('更新失败，请重试')
      }
    }
    
    const toggleUserStatus = async (user) => {
      try {
        const newStatus = !user.enabled
        await adminAPI.updateUserStatus(user.id, newStatus)
        // 重新加载用户列表
        await filterUsers(currentFilter.value)
        await loadDashboardData()
      } catch (error) {
        console.error('更新用户状态失败:', error)
        alert('更新失败，请重试')
      }
    }
    
    const goToUserDashboard = () => {
      router.push('/dashboard')
    }
    
    const handleLogout = () => {
      authStore.logout()
      router.push('/login')
    }
    
    onMounted(async () => {
      await Promise.all([
        loadDashboardData(),
        loadUsers()
      ])
    })
    
    return {
      authStore,
      dashboardData,
      users,
      filteredUsers,
      currentFilter,
      loading,
      formatDate,
      filterUsers,
      updateUserRole,
      toggleUserStatus,
      goToUserDashboard,
      handleLogout
    }
  }
}
</script>

<style scoped>
.admin-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.admin-content {
  position: relative;
  z-index: 2;
  min-height: 100vh;
}

.admin-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 15px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.user-menu {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome-text {
  color: #666;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  font-size: 14px;
}

.stats-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 36px;
  flex-shrink: 0;
}

.stat-info h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.stat-number {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #333;
}

.users-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-buttons {
  display: flex;
  gap: 8px;
}

.btn-filter {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn-filter:hover,
.btn-filter.active {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
}

.users-table-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.users-table {
  width: 100%;
  border-collapse: collapse;
}

.users-table th {
  background: rgba(0, 0, 0, 0.05);
  padding: 16px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.users-table td {
  padding: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.user-row:hover {
  background: rgba(0, 0, 0, 0.02);
}

.username {
  font-weight: 600;
  color: #333;
}

.role-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
}

.role-badge.admin {
  background: #e74c3c;
  color: white;
}

.role-badge.user {
  background: #3498db;
  color: white;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.status-badge.enabled {
  background: #27ae60;
  color: white;
}

.status-badge.disabled {
  background: #95a5a6;
  color: white;
}

.date {
  color: #666;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.role-select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}

.btn-danger {
  background: #e74c3c;
  color: white;
}

.btn-success {
  background: #27ae60;
  color: white;
}

.background-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.bg-shape {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: floatBackground 15s ease-in-out infinite;
}

.bg-shape-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: -5%;
  animation-delay: 0s;
}

.bg-shape-2 {
  width: 300px;
  height: 300px;
  bottom: 10%;
  right: -10%;
  animation-delay: 7s;
}

@keyframes floatBackground {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-30px) rotate(180deg);
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .users-table-container {
    overflow-x: auto;
  }
  
  .actions {
    flex-direction: column;
    gap: 4px;
  }
}
</style>